<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/24.
 */

namespace App\Models\Traits;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

trait ModelField
{
    /**
     * 自定义默认值参数
     * 格式为 ['field' => value, 'field2' => value].
     *
     * @var array
     */
    public $default = [];

    public function defaultValue(): void
    {
        if ($this->exists) {
            return;
        }
        $result = $this->getDefault();
        if (!$result) {
            return;
        }
        foreach ($result as $key => $val) {
            $this->{$key} = $val;
        }
    }

    public function getTableFields(): array
    {
        $results = $this->getCacheTableFields();
        if (isset($results[$this->getKeyName()])) {
            unset($results[$this->getKeyName()]);
        }

        return array_keys($results);
    }

    /**
     * 设置默认值缓存debug模式下不存储缓存数据.
     */
    protected function getCacheTableFields(): array
    {
        $sql = 'select column_name,data_type,column_default, column_comment from information_schema.columns where table_name = ? and table_schema = ?';

        $obj = DB::select($sql, [$this->getTable(), $this->getConnection()->getDatabaseName()]);
        $results = [];
        if (!$obj) {
            return $results;
        }

        foreach ($obj as $val) {
            $results[$val->column_name] = $val->column_default;
        }
        if (!Config::get('app.debug')) {
            Cache::put("table_default_{$this->getTable()}", serialize($results), now()->addWeeks());
        }

        return $results;
    }

    /**
     * 获取默认值
     *
     * @return array|mixed
     */
    protected function getDefault(): array
    {
        if ($this->default) {
            return $this->default;
        }
        $table = $this->getTable();
        if (!Config::get('app.debug')) {
            $results = Cache::get("table_default_{$table}");
            if ($results) {
                return unserialize($results);
            }
        }

        return $this->getCacheTableFields();
    }
}
